package by.semerikov.converter;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;

import by.semerikov.dao.DAOFactory;
import by.semerikov.dao.IPersonDAO;
import by.semerikov.entity.PersonEntity;
import by.semerikov.entity.ProposalEntity;
import by.semerikov.exceptions.DAOException;
import by.semerikov.model.Person;
import by.semerikov.model.Proposal;

public class ProposalConverter {

	public ProposalEntity convertToEntity(Proposal model) {
		ProposalEntity result = new ProposalEntity();
		result.setCost(model.getCost());
		result.setDescription(model.getDescription());
		if(model.getDriver()!= null)
		{
			result.setDriverId(model.getDriver().getId());
		}
		result.setFrom(model.getFrom());
		result.setId(model.getId());
		result.setName(model.getName());
		result.setState(model.getState());
		result.setTo(model.getTo());
		return result;
	}

	public Proposal convertToModel(ProposalEntity entity, Connection conn) throws DAOException  {
		//Достаем водителя из БД
		Proposal result = new Proposal();
		Person driver = null;
		if(entity.getDriverId()!=null)
		{
			PersonConverter personConverter = new PersonConverter();
			List<PersonEntity> driverEntitys = new ArrayList<PersonEntity>();
			PersonEntity exampleEntity = new PersonEntity(entity.getDriverId(), null, null, null, null, null);
			IPersonDAO pd = DAOFactory.getInstance().getPersonDAO();
			pd.setConnection(conn);
			driverEntitys = pd.read(exampleEntity);
			if(driverEntitys.size()>0)
				driver = personConverter.convertToModel(driverEntitys.get(0));
		}
		result.setCost(entity.getCost());
		result.setDescription(entity.getDescription());
		result.setDriver(driver);
		result.setFrom(entity.getFrom());
		result.setId(entity.getId());
		result.setName(entity.getName());
		result.setState(entity.getState());
		result.setTo(entity.getTo());
		return result;
	}

}
